//
//  SearchViewController.m
//  Menu
//
//  Created by dllo on 15/7/6.
//  Copyright (c) 2015年 lijiangang. All rights reserved.
//

#import "SearchViewController.h"

@interface SearchViewController ()

@end

@implementation SearchViewController

- (void)dealloc
{
    [_searchField release];
    [_searchBar release];
    [_searchHistoryTableV release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"搜索";
    UIImageView *bgImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search.jpg"]];
    bgImgView.frame = CGRectMake(0, 64 + 40*HEIGHT, MyWidth, MyHeight - 64 - 49 - 40*HEIGHT);
    [self.view addSubview:bgImgView];
    [bgImgView release];
    self.searchHistoryArray = [NSMutableArray array];
    
    self.searchAgainBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.searchAgainBtn.frame = CGRectMake(325*WIDTH, 0, 50*WIDTH, 40*HEIGHT);
    self.searchAgainBtn.backgroundColor = [UIColor whiteColor];
    [self.searchAgainBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [self.searchAgainBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.searchAgainBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.searchAgainBtn addTarget:self action:@selector(searchAgainBtnFunction) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchField = [[UITextField alloc] init];
    self.searchField.layer.borderColor = [[UIColor blackColor] CGColor];
    self.searchField.delegate = self;
    
    self.keepSearchingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.keepSearchingBtn.frame = self.searchAgainBtn.frame;
    [self.keepSearchingBtn setBackgroundColor:[UIColor whiteColor]];
    [self.keepSearchingBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [self.keepSearchingBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.keepSearchingBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.keepSearchingBtn addTarget:self action:@selector(keepSearching:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, MyWidth, 40*HEIGHT)];
    [self.searchBar setShowsCancelButton:YES];
    for (UIView *view in [[self.searchBar.subviews lastObject] subviews])
    {
        if ([view isKindOfClass:[UIButton class]])
        {
            
            self.button = (UIButton *)view;
            [self.button setTitle:@"取消" forState:UIControlStateNormal];
            [self.button addTarget:self action:@selector(stopSearching) forControlEvents:UIControlEventTouchUpInside];
            [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
    
    self.searchBar.delegate = self;
    self.searchBar.layer.borderColor =[UIColor blackColor].CGColor;
    self.searchBar.backgroundColor = [UIColor clearColor];
    //self.searchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] Size:self.searchBar.frame.size];
    self.searchBar.placeholder = @"搜索关键字";
    self.searchField = [[[self.searchBar.subviews firstObject] subviews] lastObject];
    self.searchField.backgroundColor = [UIColor whiteColor];
    [self.searchField becomeFirstResponder];
    [self.searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchField.layer.cornerRadius = 10;
    [self.searchField setLeftViewMode:UITextFieldViewModeWhileEditing];
    [self.view addSubview:self.searchBar];
    
    UILabel *hotSearchLabel = [[UILabel alloc] initWithFrame:CGRectMake(10*WIDTH, 130*HEIGHT, 150*WIDTH, 30*HEIGHT)];
    hotSearchLabel.backgroundColor = [UIColor clearColor];
    hotSearchLabel.text = @"热门搜索";
    hotSearchLabel.textColor = [UIColor whiteColor];
    hotSearchLabel.font = [UIFont systemFontOfSize:22];
    [self.view addSubview:hotSearchLabel];
    [hotSearchLabel release];
    
    UIView *hotSerachView = [[UIView alloc] initWithFrame:CGRectMake(0, hotSearchLabel.frame.origin.y + hotSearchLabel.frame.size.height, 375*WIDTH, 200*HEIGHT)];
    hotSerachView.backgroundColor = [UIColor whiteColor];
    hotSerachView.alpha = 0.6;
    [self.view addSubview:hotSerachView];
    NSMutableArray *hotArray = [NSMutableArray arrayWithObjects:@"猪肉", @"羊排", @"培根", @"鱼", @"鸡翅", @"苹果", @"奶酪", @"牛腩", @"香菇", @"豆角", @"黄瓜", @"西红柿" ,nil];
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            UIButton *hotButton = [UIButton buttonWithType:UIButtonTypeCustom];
            hotButton.frame = CGRectMake((100*j+(arc4random()%11 + 5))*WIDTH, (70*i+(arc4random()%11 + 5))*HEIGHT, (arc4random()%41 + 40)*WIDTH, (arc4random()%31 + 30)*HEIGHT);
            [hotSerachView addSubview:hotButton];
            NSString *name = [hotArray objectAtIndex:4*i+j];
            [hotButton setTitle:name forState:UIControlStateNormal];
            hotButton.titleLabel.font = [UIFont systemFontOfSize:arc4random()%11+15];
            [hotButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [hotButton sizeToFit];
            [hotButton addTarget:self action:@selector(hotBtnFunction:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    [hotSerachView release];
    
    UIImageView *lineImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line.png"]];
    lineImgView.frame = CGRectMake(10*WIDTH, hotSearchLabel.frame.origin.y + hotSearchLabel.frame.size.height, 355, 1*HEIGHT);
    //[self.view addSubview:lineImgView];
    //[lineImgView release];

    UILabel *historyLabel = [[UILabel alloc] initWithFrame:CGRectMake(10*WIDTH, lineImgView.frame.origin.y + (200 + 5)*HEIGHT, 150*WIDTH, 30*HEIGHT)];
    historyLabel.text = @"搜索历史";
    historyLabel.textColor = [UIColor whiteColor];
    historyLabel.font = [UIFont systemFontOfSize:22];
    historyLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:historyLabel];
    [historyLabel release];
    
    UILabel *cleanLabel = [[UILabel alloc] initWithFrame:CGRectMake(225*WIDTH, historyLabel.frame.origin.y, 150*WIDTH, 30*HEIGHT)];
    cleanLabel.backgroundColor = [UIColor clearColor];
    cleanLabel.text = @"清空搜索记录";
    cleanLabel.textColor = [UIColor whiteColor];
    cleanLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:cleanLabel];
    cleanLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapFunction:)];
    [cleanLabel addGestureRecognizer:tap];
    [cleanLabel release];
    
    self.searchHistoryTableV = [[UITableView alloc] initWithFrame:CGRectMake(0, historyLabel.frame.origin.y + historyLabel.frame.size.height, MyWidth, 230*HEIGHT)];
    self.searchHistoryTableV.backgroundColor = [UIColor clearColor];
    self.searchHistoryTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.searchHistoryTableV];
    self.searchHistoryTableV.delegate =self;
    self.searchHistoryTableV.dataSource = self;
    [_searchHistoryTableV release];
    [_searchBar release];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self searchAgainBtnFunction];
}

-(void)viewWillAppear:(BOOL)animated
{
    [[DataHandle shareData] openDataBase];
    [[DataHandle shareData] createSearchHistoryTable];
    [self.searchHistoryArray removeAllObjects];
    self.searchHistoryArray = [[DataHandle shareData] selectSearchHistoryTable];
    [self.searchHistoryTableV reloadData];
}

-(void)hotBtnFunction:(UIButton *)button
{
    
    [[DataHandle shareData] openDataBase];
    NSMutableArray *array = [[DataHandle shareData] selectSearchHistoryTable];
    if ([array containsObject:button.titleLabel.text])
    {
        SearchDetailViewController *searchDetailVC = [[SearchDetailViewController alloc] init];
        searchDetailVC.searchSth = button.titleLabel.text;
        [[DataHandle shareData] deleteOneOfSearch:button.titleLabel.text];
        [[DataHandle shareData] insertSearchInfoToHistoryTable:button.titleLabel.text];

        [self.navigationController pushViewController:searchDetailVC animated:YES];
    }
    else
    {
        [[DataHandle shareData] insertSearchInfoToHistoryTable:button.titleLabel.text];
        SearchDetailViewController *searchDetailVC = [[SearchDetailViewController alloc] init];
        searchDetailVC.searchSth = button.titleLabel.text;
        [self.navigationController pushViewController:searchDetailVC animated:YES];
    }
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length != 0)
    {
        [self.searchBar addSubview:self.searchAgainBtn];
        self.searchingText = searchText;
    }
    if (searchText.length == 0)
    {
        [self.searchAgainBtn removeFromSuperview];
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self.keepSearchingBtn removeFromSuperview];
}

-(void)stopSearching
{
    [self.searchField resignFirstResponder];
    [self.searchBar addSubview:self.keepSearchingBtn];
}

-(void)keepSearching:(UIButton *)button
{
    [self.keepSearchingBtn removeFromSuperview];
    [self.searchField becomeFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [self.keepSearchingBtn removeFromSuperview];
    return YES;
}

-(void)searchAgainBtnFunction
{
    
    [[DataHandle shareData] openDataBase];
    NSMutableArray *array = [[DataHandle shareData] selectSearchHistoryTable];
    if ([array containsObject:self.searchingText])
    {
        SearchDetailViewController *searchDetailVC = [[SearchDetailViewController alloc] init];
        searchDetailVC.searchSth = self.searchingText;
        [[DataHandle shareData] deleteOneOfSearch:self.searchingText];
        [[DataHandle shareData] insertSearchInfoToHistoryTable:self.searchingText];
        [self.navigationController pushViewController:searchDetailVC animated:YES];
    }
    else
    {
        [[DataHandle shareData] insertSearchInfoToHistoryTable:self.searchingText];
        SearchDetailViewController *searchDetailVC = [[SearchDetailViewController alloc] init];
        searchDetailVC.searchSth = self.searchingText;
        [self.navigationController pushViewController:searchDetailVC animated:YES];
    }
}

-(void)tapFunction:(UITapGestureRecognizer *)tap
{
    [self.searchHistoryArray removeAllObjects];
    [[DataHandle shareData] dropSearchHistoryTable];
    [self.searchHistoryTableV reloadData];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchHistoryArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellMark = @"historyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellMark];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellMark];
    }
    
    if (self.searchHistoryArray.count == 0)
    {
        return cell;
    }
    else
    {
        cell.textLabel.text = [self.searchHistoryArray objectAtIndex:indexPath.row];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.contentView.backgroundColor = [UIColor whiteColor];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.alpha = 0.6;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [[DataHandle shareData] openDataBase];
    NSString *cellText = [self.searchHistoryArray objectAtIndex:indexPath.row];
    SearchDetailViewController *searchDetailVC = [[SearchDetailViewController alloc] init];
    searchDetailVC.searchSth = cellText;
    [[DataHandle shareData] deleteOneOfSearch:cellText];
    [[DataHandle shareData] insertSearchInfoToHistoryTable:cellText];
    [self.navigationController pushViewController:searchDetailVC animated:YES];
    [searchDetailVC release];
}




//-(UIImage *)imageWithColor:(UIColor *)color Size:(CGSize)size
//{
//    CGRect rect = CGRectMake(0, 0, size.width, size.height);
//    UIGraphicsBeginImageContext(rect.size);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetFillColorWithColor(context, [color CGColor]);
//    CGContextFillRect(context, rect);
//    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return image;
//}


































- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
